package com.web3.management.controller;

import com.web3.management.dto.ApiResponse;
import com.web3.management.dto.PageResponse;
import com.web3.management.dto.response.TradeLogResponse;
import com.web3.management.service.TradeLogService;
import com.web3.management.service.SystemSettingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * 交易监控控制器
 *
 * @author Web3 Management Team
 */
@Slf4j
@RestController
@RequestMapping("/api/monitor")
@RequiredArgsConstructor
@Validated
public class MonitorController {

    private final TradeLogService tradeLogService;
    private final SystemSettingService systemSettingService;

    /**
     * 获取异常交易记录
     *
     * @param accountId 账号ID（可选）
     * @param startDate 开始日期（可选）
     * @param endDate   结束日期（可选）
     * @param page      页码
     * @param size      页大小
     * @return 异常交易列表
     */
    @GetMapping("/abnormal-transactions")
    public ApiResponse<PageResponse<TradeLogResponse>> getAbnormalTransactions(
            @RequestParam(required = false) Integer accountId,
            @RequestParam(required = false) LocalDate startDate,
            @RequestParam(required = false) LocalDate endDate,
            @RequestParam(defaultValue = "1") @Min(1) Integer page,
            @RequestParam(defaultValue = "20") @Min(1) Integer size) {

        // 使用新的异常交易查询方法
        PageResponse<TradeLogResponse> response = tradeLogService.queryAbnormalTransactions(
                accountId, startDate, endDate, page, size
        );

        return ApiResponse.success(response);
    }

    /**
     * 获取监控统计信息
     *
     * @return 统计信息
     */
    @GetMapping("/stats")
    public ApiResponse<Map<String, Object>> getMonitorStats() {
        Map<String, Object> stats = tradeLogService.getMonitorStats(LocalDate.now());
        return ApiResponse.success(stats);
    }

    /**
     * 测试通知功能
     *
     * @return 测试结果
     */
    @PostMapping("/test-notification")
    public ApiResponse<String> testNotification() {
        try {
            Map<String, Object> notificationConfig = systemSettingService.getNotificationConfig();
            String webhookUrl = (String) notificationConfig.get("webhook_url");

            if (webhookUrl == null || webhookUrl.trim().isEmpty()) {
                return ApiResponse.error("未配置通知地址");
            }

            String testMessage = "🧪 这是一条测试通知，系统配置正常！\n\n时间: " + java.time.LocalDateTime.now();

            // 发送测试通知
            // 这里可以调用TransactionMonitorService的通知方法
            return ApiResponse.success("测试通知发送成功");

        } catch (Exception e) {
            log.error("测试通知失败", e);
            return ApiResponse.error("测试通知失败: " + e.getMessage());
        }
    }
}